<%
# Copyright (C) 2011 - present Instructure, Inc.
#
# This file is part of Canvas.
#
# Canvas is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, version 3 of the License.
#
# Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
%>

  <div class="mobileLogin-Header">
    <span class="screenreader-only">
      <%= t 'Canvas by Instructure' %>
    </span>
  </div>
<%= form_for :pseudonym_session, :url => url_for({ action: :create }.merge(params.slice(:id).to_unsafe_h)), :html => {:id => "login_form", :class => "front face", :novalidate => 'novalidate', :autocomplete => "off" } do |f| %>

  <div class="ic-Form-control">
    <input
      class="ic-Input"
      autocomplete="off"
      autocorrect="off"
      placeholder="<%= @login_handle_name%>"
      type="<%= @login_handle_is_email ? 'email' : 'text' %>"
      name="pseudonym_session[unique_id]"
      value="<%= params[:pseudonym_session].try(:[], :unique_id) %>" >
  </div>
  <div class="ic-Form-control">
    <input
      class="ic-Input"
      type="password"
      name="pseudonym_session[password]"
      autocomplete="off"
      autocorrect="off"
      placeholder="<%= t :password, "Password" %>" />
  </div>
  <button
    type="submit"
    class="Button Button--primary Button--block">{{#t}}Log In{{/t}}
  </button>

  <% if request.post? && flash[:error] %>
    <div class="error"><%= flash[:error] %></div>
  <% end %>

  <div class="forgotBlock">
    <% if url = params[:canvas_login].blank? && @domain_root_account.try(:forgot_password_external_url) %>
      <%= link_to t('dont_know_password', "Forgot Password?"), url, :class => 'forgot-password' %>
    <% else %>
      <a class="forgot-password flip-to-back">{{#t}}Forgot Password?{{/t}}</a>
    <% end %>
  </div>
<% end %>
<%= form_for :pseudonym_session, :url => forgot_password_path, :html => {:id => "forgot_password_form", :class => 'back face', :autocomplete => "off" } do |f| %>
  <div class="ic-Form-control">
    <label for="pseudonym_session_unique_id_forgot" class="screenreader-only"><%= t('login_handle', "Enter your %{login_handle_name} and we'll send you a link to change your password.", :login_handle_name => @login_handle_name) %></label>
    <input
      class="ic-Input"
      autocomplete="off"
      autocorrect="off"
      type="<%= @login_handle_is_email ? 'email' : 'text' %>"
      name="pseudonym_session[unique_id_forgot]"
      value="<%= @unauthorized_user.try :email %>"
      placeholder="<%= @login_handle_name %>"
      id="pseudonym_session_unique_id_forgot" />
  </div>
  <button
    type="submit"
    class="Button Button--primary Button--block"
    data-text-while-loading="<%= t :sending, "Sending..." %>" class="request-password-button">{{#t}}Request Password{{/t}}
  </button>
  <div class="forgotBlock">
    <a class="flip-to-front">{{#t}}Back to Login{{/t}}</a>
  </div>
<% end %>
<%= # for plugin use
  render "shared/login_trailer" %>

<script>
  var eventToBindTo = ('ontouchstart' in window) ? 'touchstart' : 'click';

  document.addEventListener('DOMContentLoaded', function(){
    var $front_back_container = document.querySelector('#f1_container'),
        $flip_to_back         = document.querySelector('.flip-to-back');

    if ($flip_to_back) {
      $flip_to_back.addEventListener(eventToBindTo, function(event){
        event.preventDefault();
        addClass($front_back_container, 'flipped');
      });
    }

    document.querySelector('.flip-to-front').addEventListener(eventToBindTo, function(event){
      event.preventDefault();
      removeClass($front_back_container, 'flipped');
    });

    var $forgot_password_form = document.querySelector('#forgot_password_form');
    $forgot_password_form.addEventListener('submit', function(event){
      var $button      = $forgot_password_form.querySelector('.request-password-button'),
          originalText = $button.textContent,
          uniqueId     = $forgot_password_form.querySelector('input[name="pseudonym_session[unique_id_forgot]"]').value.trim();
      if (!uniqueId) return false;
      $button.disabled = true;
      $button.textContent = $button.getAttribute('data-text-while-loading')
      event.preventDefault();
      ajax({
        type: "POST",
        url: "/forgot_password",
        data: 'authenticity_token=' +
              encodeURIComponent($forgot_password_form.querySelector('input[name=authenticity_token]').value) +
              '&pseudonym_session%5Bunique_id_forgot%5D=' +
              encodeURIComponent(uniqueId),
        success: function(response){
          alert(ENV.RESET_SENT);
        },
        error: function(){
          alert(ENV.RESET_ERROR);
        },
        complete: function(){
          $button.textContent = originalText;
        }
      });
    });
  });

  function addClass(element, name){
    removeClass(element, name);
    element.className += ' ' + name;
  }

  function removeClass(element, name){
    regex = new RegExp('(^|\\s)' + name + '(\\s|$)');
    element.className = element.className.replace(regex, '')
  }

  function ajax(options){
    var xhr = new window.XMLHttpRequest();
    options.headers = options.headers || {}
    options.headers['X-Requested-With'] = 'XMLHttpRequest'
    if (options.data && !options.contentType) options.contentType = 'application/x-www-form-urlencoded';
    if (options.contentType) options.headers['Content-Type'] = options.contentType;

    xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
        var error = false;
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 0) {
          options.success && options.success.call(options.context, xhr.responseText, 'success', xhr);
        } else {
          error = true;
          options.error && options.error.call(options.context, xhr, 'error');
        }
        options.complete && options.complete.call(options.context, xhr, error ? 'error' : 'success');
      }
    };

    xhr.open(options.type, options.url, true);
    for (name in options.headers) xhr.setRequestHeader(name, options.headers[name]);
    xhr.send(options.data);
    return xhr;
  }
</script>
